import { Env } from '../entity'
import { EnvWithServer } from '../domain'
import { v4 as uuidv4 } from 'uuid'

/**
 * 获取项目的环境列表
 */
export async function getProjectEnvs(projectId: string): Promise<EnvWithServer[]> {
  return await window.db.all<EnvWithServer>(
    `SELECT
      e.id,
      e.name,
      e.server_id as serverId,
      e.server_path as serverPath,
      s.name as serverName
     FROM project_envs e
     LEFT JOIN servers s ON e.server_id = s.id
     WHERE e.project_id = ?`,
    [projectId]
  )
}

/**
 * 添加环境配置
 */
export async function addEnv(projectId: string, env: Omit<Env, 'id'>): Promise<string> {
  const id = uuidv4()
  await window.db.run(
    `INSERT INTO project_envs (id, project_id, name, server_id, server_path)
     VALUES (?, ?, ?, ?, ?)`,
    [id, projectId, env.name, env.serverId, env.serverPath]
  )
  return id
}

/**
 * 更新环境配置
 */
export async function updateEnv(env: Env): Promise<void> {
  await window.db.run(
    `UPDATE project_envs
     SET name = ?, server_id = ?, server_path = ?
     WHERE id = ?`,
    [env.name, env.serverId, env.serverPath, env.id]
  )
}

/**
 * 删除环境配置
 */
export async function removeEnv(id: string): Promise<void> {
  await window.db.run('DELETE FROM project_envs WHERE id = ?', [id])
}
